package sunyu.tools.activemq;

import org.apache.activemq.pool.PooledConnection;

import javax.jms.*;

/**
 * 消息发送者
 *
 * @author 孙宇
 */
public class ActiveMQSenderTemplate {

    private String name;
    private Session session;
    private MessageProducer producer;

    public ActiveMQSenderTemplate(String name,
                                  PooledConnection connection,
                                  ActiveMQDestination type,
                                  String subject) throws JMSException {
        this.name = name;
        // 事务性会话，自动确认消息
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        // 消息的目的地（Queue/Topic）
        if (type.equals(ActiveMQDestination.Topic)) {
            Topic destination = session.createTopic(subject);
            producer = session.createProducer(destination);
        } else {
            Queue destination = session.createQueue(subject);
            producer = session.createProducer(destination);
        }
        // 不持久化消息
        //producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
    }

    public String getName() {
        return name;
    }

    public Session getSession() {
        return session;
    }

    public void sendMessage(Message message) throws JMSException {
        producer.send(message);
    }

}
